﻿using Model.WXshopBuiness;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Core.WeiXin;
using Model.WeiXin;
using Services.WeiXinProject;
using Xproject.Util;
using Model.Const;

namespace WeiXinProject.Controllers
{
    public class LoginController : CommonBaseController
    {
        UserInfoServices m_UserInfoServices;

        public LoginController(UserInfoServices mUserInfoServices)
        {
            m_UserInfoServices = mUserInfoServices;
        }
        // GET: Login
        public ActionResult Index(string gotoUrl)
        {
            LogHelper.WriteFlag(" login index :goturl:"+HttpUtility.UrlDecode( gotoUrl));
            GetAndSetWXUserInfo();
            ViewBag.Domain = this.GetDomain;
            ViewBag.gotoUrl = gotoUrl;
            return View();
        }

        #region 微信授权登录拿用户相关
        void GetAndSetWXUserInfo()
        {
            string code = this.Request.QueryString["code"];
            string state = this.Request.QueryString["state"];

            if (!string.IsNullOrEmpty(code))
            {
              //  LogHelper.WriteFlag(" login index  38 "+ "code = "+code);
                #region //wx back 注册
               
                WeiXinModel.UserInfoModel userInfo = WeiXinHelper.GetUserInfo(code);              
                if (string.IsNullOrEmpty(userInfo.openid)) return;
                LogHelper.WriteFlag(" login index  46 " + "opeind = " + userInfo.openid);
                string openId = userInfo.openid;
                string nickName = userInfo.nickname;
                string headUrl = userInfo.headimgurl;
                string area = userInfo.province + userInfo.city;
                string sex = userInfo.sex.ToString();
                string unionId = userInfo.unionid;//add 2016-7-8
                if (string.IsNullOrEmpty(unionId)) unionId = openId;
                int subscribe = userInfo.subscribe;

                 WeiXinUser  user = m_UserInfoServices.GetWeiXinUserByOpenId(openId);
                
                if (user == null) //不存在就新加用户 这种情况属于没有关注，（发推广链接，直接点击查看的）
                {
                    LogHelper.WriteFlag(" login index  56 user not eixtsts! "+ nickName +" "+ openId+" "+headUrl+" "+area+" "+sex);
                    //WeiXinUser newuser = m_UserInfoServices.InsertWeiXinUserInfo(nickName, openId, headUrl, area, sex, unionId, "");
                    string zxparent = this.Request.QueryString["zxpID"];//有直销用户ID,说明是推荐而来
                    string zxusersource = this.Request.QueryString["usource"];
                    
                    string zxPlatform = CommonHelper.GetAppSettings("MessageSender");
                    int level = 0,zxus = 0;
                    long lzp = 0;
                    long.TryParse(zxparent, out lzp);
                    if (string.IsNullOrEmpty(zxusersource))
                    {
                        zxus = (int)EnumUserSource.WEB_PRODUCT;
                    }
                    else
                    {
                        int.TryParse(zxusersource, out zxus);
                    }
                    long jifeng = 10;
                    string jf = CommonHelper.GetAppSettings("REGIST_GIFT_JF");
                    long.TryParse(jf, out jifeng);
                    WeiXinUser newuser = m_UserInfoServices.InserWeiXinUserInfo_ZX(nickName, openId, headUrl, area, sex, unionId, "", lzp, zxus, zxPlatform, level,0,0,jifeng);
                    if (newuser == null)
                    {
                        LogHelper.WriteFlag(" login index  60 " + "add user erros ");
                        this.ClearWxShopSession();
                        Redirect("/CommonBase/SystemNotice?Notice=" + "尝试注册失败");
                    }
                    else
                    {
                        user = newuser;
                    }
                }                                              
                #endregion

                if (subscribe == 1)
                {
                 //   LogHelper.WriteFlag(" login index  67 " + "OK ");
                    user.LastLoginTime = DateTime.Now;
                    user.IsFocus = subscribe;
                    user.FocusTime =CommonHelper.GetTime(userInfo.subscribe_time.ToString());
                    bool res =  m_UserInfoServices.UpdateWeiXinUserInfo(user);
                  //  LogHelper.WriteFlag(" login index  72 " + "OK " + res);
                }
                else
                {
                   // LogHelper.WriteFlag(" login index  77 " + "OK ");
                    user.LastLoginTime = DateTime.Now;
                   bool res= m_UserInfoServices.UpdateWeiXinUserInfo(user);
                   // LogHelper.WriteFlag(" login index  79 " + "OK " + res);
                }
                string gotoUrl = this.Request.QueryString["gotoUrl"];
                string fromParam = this.Request.QueryString["from"];
               //  LogHelper.WriteFlag(" login index 84 check the gotoUrl is  " + gotoUrl + " and from is :"+ fromParam);
              //  LogHelper.WriteFlag(" login index  83 " + "OK ");
                ZXUserInfoModel zxuser = m_UserInfoServices.GetWeiXinZXUserInfoByOpenId(openId);
                this.SetSession(zxuser, userInfo.openid);
                //跳转到首页啊什么的
                if (!string.IsNullOrEmpty(gotoUrl))
                {
                    Response.Redirect(this.GetDomain+gotoUrl);
                }
                else
                {
                  
                    gotoUrl   = this.GetDomain + CommonHelper.GetAppSettings("Default_Site_IndexPage");//去用户中心
                 //   LogHelper.WriteFlag(" login index  74 " + "gotourl " + gotoUrl);
                    Response.Redirect(gotoUrl);
                }
            }
            else
            {
             //   LogHelper.WriteFlag(" login index 106 " + " no code " );
                GotoOAuth();
            }
        }

        void GotoOAuth()
        {
            string gotoUrl =this.Request.QueryString["gotoUrl"];
           // LogHelper.WriteInfoLog("flag+++++++++++++gotourl :" + HttpUtility.UrlDecode(gotoUrl));
            ZXUserInfoModel o =(ZXUserInfoModel) GetSession();
            if (o != null)
            {
                
                if (this.IsWxBrowser())
                {
                    gotoUrl = HttpUtility.UrlEncode(gotoUrl);
                    gotoUrl = this.GetDomain + gotoUrl;                 
                    Response.Redirect(gotoUrl); 
                }
                 
                else
                {
                    if (!string.IsNullOrEmpty(gotoUrl))
                    {
                        Response.Redirect(gotoUrl);
                    }
                    else
                    {
                        gotoUrl = this.GetDomain + CommonHelper.GetAppSettings("Default_Site_IndexPage");//去用户中心
                        Response.Redirect(gotoUrl);
                    }
                }
            }
            else
            {
                if (this.Request.Url.Host.Contains("localhost")) return;
                //if( !string.IsNullOrEmpty( isOpenWXOAuth ) && isOpenWXOAuth.ToLower().Trim() == "true" )
                if (this.IsWxBrowser())
                {
                    gotoUrl = HttpUtility.UrlEncode(gotoUrl);
                    gotoUrl = this.GetDomain + "/LoginWX.aspx?gotoUrl="+gotoUrl;
                    Response.Redirect(gotoUrl);
                }
                else
                {
                    this.Response.ClearHeaders();
                    this.Response.ClearContent();
                    Response.Redirect("/CommonBase/SystemNotice?Notice=" + "请使用微信客户端打开");
                }
            }
        }
        #endregion

        public JsonResult LoginByMaual(string userCode, string pwd,string gotourl)
        {
            var jsonData = new Object();                      
            string md5key = CommonHelper.MD5(pwd);
          //  WeiXinUser user =m_UserInfoServices.GetWeiXinUserByCode(userCode, md5key);
          ZXUserInfoModel user = m_UserInfoServices.GetWeiXinZXUserInfoByCode(userCode, md5key);
            bool result = false;
            string data = string.Empty;            
            if (user != null)
            {
                this.SetSession(user, user.OpenId);
                string gotoUrl = this.GetDomain + CommonHelper.GetAppSettings("Default_Site_IndexPage");//去用户中心
                if (!string.IsNullOrEmpty(gotourl))
                {
                    gotoUrl = this.GetDomain + gotourl;
                }
               
                result = true;
                data = gotoUrl;
            }
            else
            {
                result = false;
                data = "登录失败";
            }
            jsonData = new { Success = result, Data = data };
            return Json(jsonData);
           
            
        }




    }
}